<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  

  
  <title>promise | 前端日常</title>
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
  <meta name="description" content="1.js 事件执行机制JS 是一门单线程语言，最新的 HTML5 中提出了 Web-Worker，但 JavaScript 是单线程这一核心仍未改变。  JS 单线程基于事件循环：分为异步和同步。同步执行完，在执行异步中的内容  同步的进入主线程，异步的进入 Event Table（事件列表） 并注册函数。 当指定的事情完成时，Event Table 会将这个函数移入 Event Queue（事件">
<meta property="og:type" content="article">
<meta property="og:title" content="promise">
<meta property="og:url" content="https://coloker.gitee.io/blog/2021/06/19/promise/index.html">
<meta property="og:site_name" content="前端日常">
<meta property="og:description" content="1.js 事件执行机制JS 是一门单线程语言，最新的 HTML5 中提出了 Web-Worker，但 JavaScript 是单线程这一核心仍未改变。  JS 单线程基于事件循环：分为异步和同步。同步执行完，在执行异步中的内容  同步的进入主线程，异步的进入 Event Table（事件列表） 并注册函数。 当指定的事情完成时，Event Table 会将这个函数移入 Event Queue（事件">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://coloker.gitee.io/images/15216392-569f354ffa11d9ec.webp">
<meta property="og:image" content="https://coloker.gitee.io/images/promises.png">
<meta property="og:image" content="https://coloker.gitee.io/images/225454177.png">
<meta property="article:published_time" content="2021-06-19T08:19:11.000Z">
<meta property="article:modified_time" content="2021-06-19T09:01:25.992Z">
<meta property="article:author" content="王路路">
<meta property="article:tag" content="前端 javascript">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://coloker.gitee.io/images/15216392-569f354ffa11d9ec.webp">
  
    <link rel="alternate" href="/blog/atom.xml" title="前端日常" type="application/atom+xml">
  
  
    <link rel="icon" href="/favicon.png">
  
  
  
  
<link rel="stylesheet" href="/blog/css/style.css">

<meta name="generator" content="Hexo 5.4.0"></head>

<body>
  <div id="container">
    <div id="wrap">
      <header id="header">
  <div id="banner"></div>
  <div id="header-outer" class="outer">
    <div id="header-title" class="inner">
      <h1 id="logo-wrap">
        <a href="/blog/" id="logo">前端日常</a>
      </h1>
      
    </div>
    <div id="header-inner" class="inner">
      <nav id="main-nav">
        <a id="main-nav-toggle" class="nav-icon"></a>
        
          <a class="main-nav-link" href="/blog/">Home</a>
        
          <a class="main-nav-link" href="/blog/archives">Archives</a>
        
      </nav>
      <!-- <nav id="sub-nav">
        
          <a id="nav-rss-link" class="nav-icon" href="/blog/atom.xml" title="RSS Feed"></a>
        
        <a id="nav-search-btn" class="nav-icon" title="搜索"></a>
      </nav> -->
      <div id="search-form-wrap">
        <form action="//google.com/search" method="get" accept-charset="UTF-8" class="search-form"><input type="search" name="q" class="search-form-input" placeholder="Search"><button type="submit" class="search-form-submit">&#xF002;</button><input type="hidden" name="sitesearch" value="https://coloker.gitee.io/blog"></form>
      </div>
    </div>
  </div>
</header>
      <div class="outer">
        <section id="main"><article id="post-promise" class="article article-type-post" itemscope itemprop="blogPost">
  <div class="article-meta">
    <a href="/blog/2021/06/19/promise/" class="article-date">
  <time datetime="2021-06-19T08:19:11.000Z" itemprop="datePublished">2021-06-19</time>
</a>
    
  <div class="article-category">
    <a class="article-category-link" href="/blog/categories/JavaScript/">JavaScript</a>
  </div>

  </div>
  <div class="article-inner">
    
    
      <header class="article-header">
        
  
    <h1 class="article-title" itemprop="name">
      promise
    </h1>
  

      </header>
    
    <div class="article-entry" itemprop="articleBody">
      
        <h3 id="1-js-事件执行机制"><a href="#1-js-事件执行机制" class="headerlink" title="1.js 事件执行机制"></a>1.js 事件执行机制</h3><p>JS 是一门单线程语言，最新的 HTML5 中提出了 Web-Worker，但 JavaScript 是单线程这一核心仍未改变。</p>
<p><img src="/images/15216392-569f354ffa11d9ec.webp" alt="img"></p>
<p><strong>JS 单线程基于事件循环</strong>：分为异步和同步。同步执行完，在执行异步中的内容</p>
<ul>
<li>同步的进入主线程，异步的进入 Event Table（事件列表） 并注册函数。</li>
<li>当指定的事情完成时，Event Table 会将这个函数移入 Event Queue（事件队列）。</li>
<li>主线程内的任务执行完毕为空，会去 Event Queue 读取对应的函数，进入主线程执行。</li>
<li>上述过程会不断重复，也就是常说的 Event Loop（事件循环）。</li>
</ul>
<p>任务队列又分为<strong>宏任务队列</strong>和<strong>微任务队列</strong></p>
<ul>
<li>宏任务（MacroTask）：整体代码 Script、UI 渲染、I/O、postMessage、MessageChannel、requestAnimationFrame、setTimeout、setInterval、setImmediate（Node.js 环境）</li>
<li>微任务（MicroTask）：Promise.then()、catch、finally、process.nextTick（Node.js 环境）、MutaionObserver</li>
</ul>
<p><strong>事件循环</strong></p>
<ol>
<li>进入脚本执行宏任务，自上而下运行</li>
<li>遇到同步代码按顺序执行，遇到宏任务放入宏任务队列，遇到微任务放入微任务队列</li>
<li>执行完当前宏任务，执行微任务中执行完并正在等待执行的任务</li>
<li>执行下一个宏任务，这样周而复始的执行顺序被称为事件循环</li>
</ol>
<p>JS 的执行顺序和声明以及引用的顺序有关，先声明的顺序先执行，后声明的顺序后执行（如果有两个同名方法，后声明的会覆盖先声明的）</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 以下代码在 Node 环境运行：process.nextTick 由 Node 提供</span></span><br><span class="line"><span class="built_in">console</span>.log(<span class="string">&quot;1&quot;</span>)</span><br><span class="line"><span class="built_in">setTimeout</span>(<span class="function"><span class="keyword">function</span> (<span class="params"></span>) </span>&#123;</span><br><span class="line">  <span class="built_in">console</span>.log(<span class="string">&quot;2&quot;</span>)</span><br><span class="line">  process.nextTick(<span class="function"><span class="keyword">function</span> (<span class="params"></span>) </span>&#123;</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">&quot;3&quot;</span>)</span><br><span class="line">  &#125;)</span><br><span class="line">  <span class="keyword">new</span> <span class="built_in">Promise</span>(<span class="function"><span class="keyword">function</span> (<span class="params">resolve</span>) </span>&#123;</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">&quot;4&quot;</span>)</span><br><span class="line">    resolve()</span><br><span class="line">  &#125;).then(<span class="function"><span class="keyword">function</span> (<span class="params"></span>) </span>&#123;</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">&quot;5&quot;</span>)</span><br><span class="line">  &#125;)</span><br><span class="line">&#125;)</span><br><span class="line"></span><br><span class="line">process.nextTick(<span class="function"><span class="keyword">function</span> (<span class="params"></span>) </span>&#123;</span><br><span class="line">  <span class="built_in">console</span>.log(<span class="string">&quot;6&quot;</span>)</span><br><span class="line">&#125;)</span><br><span class="line"></span><br><span class="line"><span class="keyword">new</span> <span class="built_in">Promise</span>(<span class="function"><span class="keyword">function</span> (<span class="params">resolve</span>) </span>&#123;</span><br><span class="line">  <span class="built_in">console</span>.log(<span class="string">&quot;7&quot;</span>)</span><br><span class="line">  resolve()</span><br><span class="line">&#125;).then(<span class="function"><span class="keyword">function</span> (<span class="params"></span>) </span>&#123;</span><br><span class="line">  <span class="built_in">console</span>.log(<span class="string">&quot;8&quot;</span>)</span><br><span class="line">&#125;)</span><br><span class="line"></span><br><span class="line"><span class="built_in">setTimeout</span>(<span class="function"><span class="keyword">function</span> (<span class="params"></span>) </span>&#123;</span><br><span class="line">  <span class="built_in">console</span>.log(<span class="string">&quot;9&quot;</span>)</span><br><span class="line">  process.nextTick(<span class="function"><span class="keyword">function</span> (<span class="params"></span>) </span>&#123;</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">&quot;10&quot;</span>)</span><br><span class="line">  &#125;)</span><br><span class="line">  <span class="keyword">new</span> <span class="built_in">Promise</span>(<span class="function"><span class="keyword">function</span> (<span class="params">resolve</span>) </span>&#123;</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">&quot;11&quot;</span>)</span><br><span class="line">    resolve()</span><br><span class="line">  &#125;).then(<span class="function"><span class="keyword">function</span> (<span class="params"></span>) </span>&#123;</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">&quot;12&quot;</span>)</span><br><span class="line">  &#125;)</span><br><span class="line">)</span><br><span class="line"></span><br><span class="line"><span class="comment">// 最终输出：1 7 6 8 2 4 3 5 9 11 10 12</span></span><br></pre></td></tr></table></figure>

<h2 id="2-promise-的介绍"><a href="#2-promise-的介绍" class="headerlink" title="2.promise 的介绍"></a>2.promise 的介绍</h2><p><strong>Promise</strong> 对象用于表示一个异步操作的最终完成 (或失败)及其结果值。</p>
<p>一个 <code>Promise</code> 对象代表一个在这个 promise 被创建出来时不一定已知的值。它让您能够把异步操作最终的成功返回值或者失败原因和相应的处理程序关联起来。 这样使得异步方法可以像同步方法那样返回值：异步方法并不会立即返回最终的值，而是会返回一个 <em>promise</em>，以便在未来某个时候把值交给使用者。</p>
<p>一个 <code>Promise</code> 必然处于以下几种状态之一：</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">- *待定（pending）*: 初始状态，既没有被兑现，也没有被拒绝。</span><br><span class="line">- *已兑现（fulfilled）*: 意味着操作成功完成。</span><br><span class="line">- *已拒绝（rejected）*: 意味着操作失败。</span><br></pre></td></tr></table></figure>


<p>待定状态的 Promise 对象要么会通过一个值<em>被兑现（fulfilled）</em>，要么会通过一个原因（错误）<em>被拒绝（rejected）</em>。当这些情况之一发生时，我们用 promise 的 then 方法排列起来的相关处理程序就会被调用。如果 promise 在一个相应的处理程序被绑定时就已经被兑现或被拒绝了，那么这个处理程序就会被调用，因此在完成异步操作和绑定处理方法之间不会存在竞争状态。</p>
<p>因为 <code>Promise.prototype.then</code> 和 <code>Promise.prototype.catch</code> 方法返回的是 promise， 所以它们可以被链式调用。</p>
<p><img src="/images/promises.png" alt="img"></p>
<p><strong>不要和惰性求值混淆：</strong> 有一些语言中有惰性求值和延时计算的特性，它们也被称为“promises”，例如 Scheme。JavaScript 中的 promise 代表的是已经正在发生的进程， 而且可以通过回调函数实现链式调用。 如果您想对一个表达式进行惰性求值，就考虑一下使用无参数的”<a target="_blank" rel="noopener" href="https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Functions/Arrow_functions">箭头函数</a>“: <code>f = () =&gt;</code><em><code>表达式</code></em> 来创建惰性求值的表达式<em>，</em>使用 <code>f()</code> 求值。</p>
<p><strong>注意：</strong> 如果一个 promise 已经被兑现（fulfilled）或被拒绝（rejected），那么我们也可以说它处于<em>已敲定（settled）</em>状态。您还会听到一个经常跟 promise 一起使用的术语：<em>已决议（resolved）</em>，它表示 promise 已经处于已敲定(settled)状态，或者为了匹配另一个 promise 的状态被”锁定”了。Domenic Denicola 的 <a target="_blank" rel="noopener" href="https://github.com/domenic/promises-unwrapping/blob/master/docs/states-and-fates.md">States and fates</a> 中有更多关于 promise 术语的细节可以供您参考。</p>
<h3 id="3-手写promise："><a href="#3-手写promise：" class="headerlink" title="3.手写promise："></a>3.手写promise：</h3><p>什么是高阶函数：(<a target="_blank" rel="noopener" href="https://www.cnblogs.com/wuhairui/p/10632596.html">https://www.cnblogs.com/wuhairui/p/10632596.html</a>)</p>
<p>所谓<strong>高阶函数</strong>，就是函数中可以传入另一个函数作为参数的函数。</p>
<p><img src="/images/225454177.png" alt="img"></p>
<p>高阶函数的示例：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// Promise 可以传入函数作为参数</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> say =<span class="function">() =&gt;</span>&#123;</span><br><span class="line">  <span class="built_in">console</span>.log(<span class="string">&quot;hello&quot;</span>)</span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">// 希望在调用say方法之前做一些事情  ==&gt;给函数say拓展一些功能</span></span><br><span class="line"><span class="built_in">Function</span>.prototype.before=<span class="function"><span class="keyword">function</span>(<span class="params">fn</span>)</span>&#123;</span><br><span class="line">  <span class="keyword">return</span> <span class="function">()=&gt;</span>&#123; </span><br><span class="line">     fn()</span><br><span class="line">     <span class="built_in">this</span>()</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">let</span> speak=say.before(<span class="function"><span class="keyword">function</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">  <span class="built_in">console</span>.log(<span class="string">&#x27;说话前,清一下嗓子&#x27;</span>)</span><br><span class="line">&#125;)</span><br><span class="line">speak()</span><br><span class="line"></span><br><span class="line"><span class="comment">// ===&gt;所谓高阶函数，就是函数中可以传入另一个函数作为参数的函数。</span></span><br></pre></td></tr></table></figure>

<p>函数柯里化</p>
<p>把接受多个参数的函数变换成接受一个单一参数（最初函数的第一个参数）的函数，并且返回接受余下的参数而且返回结果的新函数的技术。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">checkType</span>(<span class="params">type</span>)</span>&#123;</span><br><span class="line">  <span class="keyword">return</span> <span class="function">(<span class="params">content</span>)=&gt;</span>&#123;</span><br><span class="line">   <span class="keyword">return</span>  <span class="built_in">Object</span>.prototype.toString.call(content)===<span class="string">`[object <span class="subst">$&#123;type&#125;</span>]`</span></span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">let</span> isString =checkType(<span class="string">&quot;String&quot;</span>)</span><br><span class="line"><span class="keyword">let</span> isBoolean =checkType(<span class="string">&quot;Boolean&quot;</span>)</span><br><span class="line"><span class="keyword">let</span> flag1 =isString(<span class="string">&#x27;aaa&#x27;</span>)</span><br><span class="line"><span class="keyword">let</span> flag2 =isBoolean(<span class="literal">true</span>)</span><br><span class="line"></span><br><span class="line"><span class="built_in">console</span>.log(flag1,flag2)</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<p>异步并发问题</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 异步并发问题</span></span><br><span class="line"><span class="comment">// 需求：同时发送多个请求 我希望拿到最终结果 &#123;name,age,address&#125;</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> fs=<span class="built_in">require</span>(<span class="string">&#x27;fs&#x27;</span>)</span><br><span class="line"></span><br><span class="line"><span class="comment">// 并发操作 两个操作互不影响</span></span><br><span class="line"><span class="keyword">const</span> after=<span class="function">(<span class="params">times,fn</span>)=&gt;</span><span class="function">()=&gt;</span>--times==<span class="number">0</span>&amp;&amp;fn()</span><br><span class="line"></span><br><span class="line"><span class="keyword">let</span> out=after(<span class="number">2</span>,<span class="function">()=&gt;</span>&#123;</span><br><span class="line">  <span class="built_in">console</span>.log(rederObj)</span><br><span class="line">&#125;)</span><br><span class="line"></span><br><span class="line"><span class="keyword">let</span> rederObj=&#123;&#125;</span><br><span class="line"></span><br><span class="line">fs.readFile(<span class="string">&#x27;./test1.txt&#x27;</span>,<span class="string">&#x27;utf8&#x27;</span>,<span class="function"><span class="keyword">function</span>(<span class="params">err,data</span>)</span>&#123;</span><br><span class="line">  rederObj.name=data</span><br><span class="line">  out()</span><br><span class="line">&#125;)</span><br><span class="line"></span><br><span class="line">fs.readFile(<span class="string">&#x27;./test2.txt&#x27;</span>,<span class="string">&#x27;utf8&#x27;</span>,<span class="function"><span class="keyword">function</span>(<span class="params">err,data</span>)</span>&#123;</span><br><span class="line">  rederObj.age=data</span><br><span class="line">  out()</span><br><span class="line">&#125;)</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<p>发布订阅模式</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 订阅就是讲要做的事情先存储好，稍后发布的时候让订阅好的事情依次执行</span></span><br><span class="line"><span class="keyword">const</span> fs=<span class="built_in">require</span>(<span class="string">&#x27;fs&#x27;</span>)</span><br><span class="line"><span class="keyword">let</span> e=&#123;</span><br><span class="line">  <span class="attr">arr</span>:[],</span><br><span class="line">  <span class="comment">// 订阅</span></span><br><span class="line">  <span class="function"><span class="title">on</span>(<span class="params">fn</span>)</span>&#123;</span><br><span class="line">    <span class="built_in">this</span>.arr.push(fn)</span><br><span class="line">  &#125;,</span><br><span class="line">  <span class="comment">// 发布 (触发)</span></span><br><span class="line">  <span class="function"><span class="title">emit</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">    <span class="built_in">this</span>.arr.forEach(<span class="function"><span class="params">fn</span>=&gt;</span>fn())</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">e.on(<span class="function">()=&gt;</span>&#123;</span><br><span class="line">  <span class="built_in">console</span>.log(<span class="string">&#x27;这是一个订阅事件&#x27;</span>)</span><br><span class="line">&#125;)</span><br><span class="line"></span><br><span class="line"><span class="keyword">let</span> renderObj=&#123;&#125;</span><br><span class="line">e.on(<span class="function">()=&gt;</span>&#123;</span><br><span class="line">  <span class="keyword">if</span>(<span class="built_in">Object</span>.keys(renderObj).length==<span class="number">2</span>)&#123;</span><br><span class="line">   <span class="built_in">console</span>.log(<span class="string">&#x27;都读取完毕了&#x27;</span>,renderObj)</span><br><span class="line">  &#125;</span><br><span class="line">&#125;)</span><br><span class="line"></span><br><span class="line">fs.readFile(<span class="string">&#x27;./test1.txt&#x27;</span>,<span class="string">&#x27;utf8&#x27;</span>,<span class="function"><span class="keyword">function</span>(<span class="params">err,data</span>)</span>&#123;</span><br><span class="line">  renderObj.name=data</span><br><span class="line">  e.emit() <span class="comment">// 发布</span></span><br><span class="line">&#125;)</span><br><span class="line"></span><br><span class="line">fs.readFile(<span class="string">&#x27;./test2.txt&#x27;</span>,<span class="string">&#x27;utf8&#x27;</span>,<span class="function"><span class="keyword">function</span>(<span class="params">err,data</span>)</span>&#123;</span><br><span class="line">  renderObj.age=data</span><br><span class="line">  e.emit() <span class="comment">// 发布</span></span><br><span class="line">&#125;)</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<p>观察者模式：</p>
<p>当对象间存在一对多关系时，则使用观察者模式（Observer Pattern）。比如，当一个对象被修改时，则会自动通知依赖它的对象。观察者模式属于行为型模式。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 当对象间存在一对多关系时，则使用观察者模式（Observer Pattern）。</span></span><br><span class="line"><span class="comment">// 比如，当一个对象被修改时，则会自动通知依赖它的对象。观察者模式属于行为型模式。</span></span><br><span class="line"><span class="comment">// 被观察者</span></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Subject</span> </span>&#123;</span><br><span class="line">  <span class="function"><span class="title">constructor</span>(<span class="params">name</span>)</span> &#123;</span><br><span class="line">    <span class="built_in">this</span>.name=name</span><br><span class="line">    <span class="built_in">this</span>.arr=[]</span><br><span class="line">    <span class="built_in">this</span>.state=<span class="string">&#x27;我很开心&#x27;</span></span><br><span class="line">  &#125;</span><br><span class="line">  <span class="function"><span class="title">attach</span>(<span class="params">observer</span>)</span>&#123;</span><br><span class="line">    <span class="comment">// 注册观察者 基于发布订阅者模式</span></span><br><span class="line">    <span class="built_in">this</span>.arr.push(observer)</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="function"><span class="title">setState</span>(<span class="params">newState</span>)</span>&#123;</span><br><span class="line">   <span class="built_in">this</span>.state=newState</span><br><span class="line">   <span class="built_in">this</span>.arr.forEach(<span class="function"><span class="params">o</span>=&gt;</span>o.update(<span class="built_in">this</span>))</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 观察者</span></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Observer</span> </span>&#123;</span><br><span class="line">  <span class="function"><span class="title">constructor</span>(<span class="params">name</span>)</span> &#123;</span><br><span class="line">    <span class="built_in">this</span>.name=name</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="function"><span class="title">update</span>(<span class="params">s</span>)</span>&#123;</span><br><span class="line">    <span class="built_in">console</span>.log(s.name+<span class="string">&#x27;当前状态是：&#x27;</span>+s.state+<span class="string">&#x27;,观察者：&#x27;</span>+<span class="built_in">this</span>.name)</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">let</span> s=<span class="keyword">new</span> Subject(<span class="string">&#x27;baby&#x27;</span>)</span><br><span class="line"></span><br><span class="line"><span class="keyword">let</span> father=<span class="keyword">new</span> Observer(<span class="string">&#x27;father&#x27;</span>)</span><br><span class="line"><span class="keyword">let</span> mother=<span class="keyword">new</span> Observer(<span class="string">&#x27;mother&#x27;</span>)</span><br><span class="line"></span><br><span class="line"><span class="comment">// s.attach(father)</span></span><br><span class="line"><span class="comment">// s.attach(mother)</span></span><br><span class="line"><span class="built_in">console</span>.log(s.state)</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="comment">// 使用观察者模式 实现对被观察者状态的检测</span></span><br><span class="line">s.setState(<span class="string">&#x27;不开心&#x27;</span>)</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<p>promise</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 一个 Promise 对象代表一个在这个 promise </span></span><br><span class="line"><span class="comment">// 被创建出来时不一定已知的值。它让您能够把异步操作最终的成功返回值或者失败原因和相应的处理程序关联起来。 </span></span><br><span class="line"><span class="comment">// 这样使得异步方法可以像同步方法那样返回值：异步方法并不会立即返回最终的值，而是会返回一个 promise，</span></span><br><span class="line"><span class="comment">// 以便在未来某个时候把值交给使用者。</span></span><br><span class="line"></span><br><span class="line"><span class="comment">// 一个 Promise 必然处于以下几种状态之一：</span></span><br><span class="line"><span class="comment">// - *待定（pending）*: 初始状态，既没有被兑现，也没有被拒绝。</span></span><br><span class="line"><span class="comment">// - *已兑现（fulfilled）*: 意味着操作成功完成。</span></span><br><span class="line"><span class="comment">// - *已拒绝（rejected）*: 意味着操作失败。</span></span><br><span class="line"><span class="comment">// $ajax(&#123;</span></span><br><span class="line"><span class="comment">//   success:()=&gt;&#123;</span></span><br><span class="line"><span class="comment">//     $ajax(&#123;</span></span><br><span class="line"><span class="comment">//       success:()=&gt;&#123;</span></span><br><span class="line"><span class="comment">//         $ajax(&#123;</span></span><br><span class="line"><span class="comment">//           success:()=&gt;&#123;</span></span><br><span class="line">            </span><br><span class="line"><span class="comment">//           &#125;</span></span><br><span class="line"><span class="comment">//         &#125;)</span></span><br><span class="line"><span class="comment">//       &#125;</span></span><br><span class="line"><span class="comment">//     &#125;)</span></span><br><span class="line"><span class="comment">//   &#125;</span></span><br><span class="line"><span class="comment">// &#125;)</span></span><br><span class="line"></span><br><span class="line"><span class="comment">// ==&gt;promise用来处理【回调地狱】</span></span><br><span class="line"><span class="comment">// ==&gt;promise用来处理【多个请求并发问题】</span></span><br><span class="line"><span class="keyword">let</span> promise= <span class="keyword">new</span> <span class="built_in">Promise</span>(<span class="function">(<span class="params">resolve,reject</span>)=&gt;</span>&#123;</span><br><span class="line">    resolve(<span class="string">&#x27;成功&#x27;</span>)</span><br><span class="line">&#125;)</span><br><span class="line">promise.then(<span class="function">(<span class="params">success</span>)=&gt;</span>&#123;</span><br><span class="line">  <span class="built_in">console</span>.log(<span class="string">&#x27;success&#x27;</span>,success)</span><br><span class="line">&#125;,<span class="function">(<span class="params">err</span>)=&gt;</span>&#123;</span><br><span class="line">  <span class="built_in">console</span>.log(<span class="string">&#x27;err&#x27;</span>,err)</span><br><span class="line">&#125;)</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<p>一个promise示例：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">console</span>.log(<span class="string">&#x27;---------mm---------&#x27;</span>)</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> PENDING=<span class="string">&#x27;PENDING&#x27;</span></span><br><span class="line"><span class="keyword">const</span> FULFILLED=<span class="string">&#x27;FULFILLED&#x27;</span></span><br><span class="line"><span class="keyword">const</span> REJECTED=<span class="string">&#x27;REJECTED&#x27;</span></span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Promise</span></span>&#123;</span><br><span class="line">  <span class="function"><span class="title">constructor</span>(<span class="params">executor</span>)</span> &#123;</span><br><span class="line">    <span class="built_in">this</span>.status=PENDING</span><br><span class="line">    <span class="built_in">this</span>.value=<span class="literal">undefined</span></span><br><span class="line">    <span class="built_in">this</span>.reason=<span class="literal">undefined</span></span><br><span class="line">    <span class="built_in">this</span>.onResolvedCallbacks=[]</span><br><span class="line">    <span class="built_in">this</span>.onRejectedCallbacks=[]</span><br><span class="line">    <span class="keyword">let</span> resolve=<span class="function">(<span class="params">value</span>)=&gt;</span>&#123;</span><br><span class="line">      <span class="keyword">if</span>(<span class="built_in">this</span>.status==PENDING)&#123;</span><br><span class="line">        <span class="built_in">this</span>.status=FULFILLED</span><br><span class="line">        <span class="built_in">this</span>.value=value</span><br><span class="line">        <span class="built_in">this</span>.onResolvedCallbacks.forEach(<span class="function"><span class="params">fn</span>=&gt;</span>fn())</span><br><span class="line">      &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">let</span> reject=<span class="function">(<span class="params">reason</span>)=&gt;</span>&#123;</span><br><span class="line">      <span class="keyword">if</span>(<span class="built_in">this</span>.status==PENDING)&#123;</span><br><span class="line">        <span class="built_in">this</span>.status=REJECTED</span><br><span class="line">        <span class="built_in">this</span>.reason=reason</span><br><span class="line">        <span class="built_in">this</span>.onRejectedCallbacks.forEach(<span class="function"><span class="params">fn</span>=&gt;</span>fn())</span><br><span class="line">      &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// executor 执行的时候需要传入两个参数，给用户来改变状态</span></span><br><span class="line">    <span class="keyword">try</span>&#123;</span><br><span class="line">      executor(resolve,reject)</span><br><span class="line">    &#125;<span class="keyword">catch</span>(e)&#123;</span><br><span class="line">      reject(e)</span><br><span class="line">    &#125;</span><br><span class="line">  </span><br><span class="line">  &#125;</span><br><span class="line">  <span class="function"><span class="title">then</span>(<span class="params">onFulfilled,onRejected</span>)</span>&#123;</span><br><span class="line">    <span class="keyword">if</span>(<span class="built_in">this</span>.status===FULFILLED)&#123;</span><br><span class="line">      onFulfilled(<span class="built_in">this</span>.value)</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">if</span>(<span class="built_in">this</span>.status===REJECTED)&#123;</span><br><span class="line">      onRejected(<span class="built_in">this</span>.reason)</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">if</span>(<span class="built_in">this</span>.status===PENDING)&#123;</span><br><span class="line">     <span class="built_in">this</span>.onResolvedCallbacks.push(<span class="function">()=&gt;</span>&#123;</span><br><span class="line">      onFulfilled(<span class="built_in">this</span>.value)</span><br><span class="line">     &#125;)</span><br><span class="line"></span><br><span class="line">     <span class="built_in">this</span>.onRejectedCallbacks.push(<span class="function">()=&gt;</span>&#123;</span><br><span class="line">      onFulfilled(<span class="built_in">this</span>.value)</span><br><span class="line">     &#125;)</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="built_in">module</span>.exports=<span class="built_in">Promise</span></span><br></pre></td></tr></table></figure>
      
    </div>
    <footer class="article-footer">
      <a data-url="https://coloker.gitee.io/blog/2021/06/19/promise/" data-id="ckq3tmkt30001ksnrf56yd8el" class="article-share-link bdsharebuttonbox" data-cmd="more">分享</a>
      <script>window._bd_share_config={"common":{"bdSnsKey":{},"bdText":"","bdMini":"1","bdMiniList":false,"bdPic":"","bdStyle":"2","bdSize":"16"},"share":{}};with(document)0[(getElementsByTagName('head')[0]||body).appendChild(createElement('script')).src='http://bdimg.share.baidu.com/static/api/js/share.js?v=89860593.js?cdnversion='+~(-new Date()/36e5)];</script>
      
      
    </footer>
  </div>
  
    
<nav id="article-nav">
  
  
    <a href="/blog/2021/06/19/%E9%97%AD%E5%8C%85/" id="article-nav-older" class="article-nav-link-wrap">
      <strong class="article-nav-caption">Older</strong>
      <div class="article-nav-title">闭包</div>
    </a>
  
</nav>

  
</article>

</section>
        
          <aside id="sidebar">
  
    
  <div class="widget-wrap">
    <h3 class="widget-title">分类</h3>
    <div class="widget">
      <ul class="category-list"><li class="category-list-item"><a class="category-list-link" href="/blog/categories/JavaScript/">JavaScript</a></li><li class="category-list-item"><a class="category-list-link" href="/blog/categories/Start/">Start</a></li></ul>
    </div>
  </div>


  
    

  
    
  
    
  <div class="widget-wrap">
    <h3 class="widget-title">归档</h3>
    <div class="widget">
      <ul class="archive-list"><li class="archive-list-item"><a class="archive-list-link" href="/blog/archives/2021/06/">六月 2021</a></li></ul>
    </div>
  </div>


  
    
  <div class="widget-wrap">
    <h3 class="widget-title">最新文章</h3>
    <div class="widget">
      <ul>
        
          <li>
            <a href="/blog/2021/06/19/promise/">promise</a>
          </li>
        
          <li>
            <a href="/blog/2021/06/19/%E9%97%AD%E5%8C%85/">闭包</a>
          </li>
        
          <li>
            <a href="/blog/2021/06/19/hello-world/">自我介绍</a>
          </li>
        
      </ul>
    </div>
  </div>

  
</aside>
        
      </div>
      <footer id="footer">
  
  <div class="outer">
    <div id="footer-info" class="inner">
      &copy; 2021 王路路<br>
      邮箱：wanglulugg@gmail.com<br />
    </div>
  </div>
</footer>
    </div>
    <nav id="mobile-nav">
  
    <a href="/blog/" class="mobile-nav-link">Home</a>
  
    <a href="/blog/archives" class="mobile-nav-link">Archives</a>
  
</nav>
    

<script src="https://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js"></script>


  
<link rel="stylesheet" href="/blog/fancybox/jquery.fancybox.css">

  
<script src="/blog/fancybox/jquery.fancybox.pack.js"></script>




<script src="/blog/js/script.js"></script>




  </div>
</body>
</html>